package cn.cycleif.component.file.impl;

import cn.cycleif.component.file.BaseFileUploadStrategy;
import cn.cycleif.enums.FileManageEnum;
import cn.cycleif.exception.BaseException;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @Date: 2024/9/14-15:53
 * @Desc:
 */
@Service("minioStrategyImpl")
@Slf4j
public class MinioStrategyImpl extends BaseFileUploadStrategy {

  @Resource
  private MinioClient minioClient;

  private final String BUCKET_NAME = "default";

  protected MinioStrategyImpl() {
    super(FileManageEnum.MINIO);
  }

  @Override
  protected boolean check() {
    return false;
  }

  @Override
  public String upload(MultipartFile file) {
    setNewFileName(file.getOriginalFilename());

    try {
      boolean found = minioClient.bucketExists(
          BucketExistsArgs.builder()
                          .bucket(BUCKET_NAME)
                          .build());
      if (!found) {
        minioClient.makeBucket(
            MakeBucketArgs.builder()
                          .bucket(BUCKET_NAME)
                          .build());
        log.info("create bucket" + BUCKET_NAME);
      }
      PutObjectArgs args =
          PutObjectArgs.builder()
                       .bucket(BUCKET_NAME)
                       .object(newFileName)
                       .stream(file.getInputStream(), file.getSize(), -1)
                       .contentType(file.getContentType())
                       .build();

      minioClient.putObject(args);
    } catch (MinioException e) {
      log.error("Error occurred: " + e + "\nHTTP trace: " + e.httpTrace());
    } catch (IOException | InvalidKeyException | NoSuchAlgorithmException e) {
      throw new BaseException("文件上传失败");
    }
    return getUrl();
  }

  private String getUrl() {
    return BUCKET_NAME + newFileName;
  }

  @Override
  public boolean remove(String... fileName) {
    return false;
  }
}
